package com.hzchendou.blog.demo.resource.service.security;

import com.hzchendou.blog.demo.common.enums.RoleEnums;
import com.hzchendou.blog.demo.resource.service.RoleService;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Service;

/**
 * 角色权限元数据服务
 *
 * @Date: 2022-05-25 11:56
 * @since: 1.0
 */
@Service
public class RolePermissionMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private RoleService roleService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object)
            throws IllegalArgumentException {
        FilterInvocation invocation = (FilterInvocation) object;
        String url = invocation.getRequestUrl();
        Collection<ConfigAttribute> roles = roleService.getRoleByPath(url);
        if (roles != null && roles.size() > 0) {
            return roles;
        }
        //没有匹配上的资源，禁止访问，设置不存在的访问权限
        return SecurityConfig.createList(RoleEnums.ROLE_REFUSE.name());
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return roleService.getAllRoles();
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
